package cn.com.bluemoon.daps.standard.service.impl;

import cn.com.bluemoon.daps.model.entity.DapDataModel;
import cn.com.bluemoon.daps.model.entity.DapDataModelTable;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableField;
import cn.com.bluemoon.daps.standard.entity.*;
import cn.com.bluemoon.daps.common.constant.DapConstant;
import cn.com.bluemoon.daps.standard.common.report.AbstractReportCheck;
import cn.com.bluemoon.daps.model.dto.ModelDto;
import cn.com.bluemoon.daps.model.dto.ModelTableDto;
import cn.com.bluemoon.daps.standard.service.DapAuditChinResultService;
import cn.com.bluemoon.daps.standard.service.DapAuditFieldChinResultService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 生成表
 *
 * @author Jarod.Kong
 * @date 2020/9/25 16:40
 */
@Component(DapConstant.AUDIT_SYSTEM_REPORT_CHINESE)
@Slf4j
public class ModelChineseReportCheckImpl extends AbstractReportCheck<DapAuditChinResult> {
    @Resource
    private DapAuditFieldChinResultService auditFieldChinResultService;

    @Resource
    private DapAuditChinResultService auditChinResultService;

    /**
     * @return 报告实现函数
     */
    @Override
    public Function<ModelTableDto, DapAuditChinResult> reportCheckFunc(ModelDto modelDto) {
        DapDataModel model = modelDto.getModel();
        String sysAuditResultId = modelDto.getSysAuditCheckResultId();
        return tableModelDto -> {
            String chinResultId = IdWorker.getIdStr();
            List<DapDataModelTableField> fields = tableModelDto.getFields();
            int markErrorFieldSize = checkAuditChiFieldSaveBatch(chinResultId, fields);
            DapDataModelTable table = tableModelDto.getTable();
            log.info("批量写入表{}-字段中文检查报告信息，size：{}", table.getEngName(), fields.size());
            DapAuditChinResult dapAuditChinResult = new DapAuditChinResult();
            dapAuditChinResult.setId(chinResultId);
            dapAuditChinResult.setTableId(table.getId());
            dapAuditChinResult.setTableName(table.getEngName());
            dapAuditChinResult.setTableChinName(table.getName());
            dapAuditChinResult.setModelId(model.getId());
            dapAuditChinResult.setModelName(model.getName());
            dapAuditChinResult.setFieldTotal(String.valueOf(fields.size()));
            dapAuditChinResult.setSystemAuditResultId(sysAuditResultId);
            final int errorFields = markErrorFieldSize;
            final int fieldTotal = fields.size();
            final String tableChiName = table.getName();
            dapAuditChinResult.setReason(null);
            if (StringUtils.isBlank(tableChiName)) {
                dapAuditChinResult.setReason("表中文名称为空");
            }
            dapAuditChinResult.setIsPassed(1);
            if (errorFields > 0) {
                dapAuditChinResult.setIsPassed(0);
            }
            dapAuditChinResult.setFieldCoincidenceRate(formatPercent((fieldTotal-errorFields), fieldTotal));
            auditChinResultService.save(dapAuditChinResult);
            log.info("写入表{}，中文检查信息，size:{}", table.getEngName(), 1);
            return dapAuditChinResult;
        };
    }

    /**
     * 基于结果定义是否未通过
     *
     * @param list
     * @return
     */
    @Override
    public boolean checkPass(List<DapAuditChinResult> list) {
        return list.stream().allMatch(d -> d.getIsPassed() == 1);
    }

    /**
     * 保存稽核中文字段
     *
     * @param chinResultId
     * @param fields
     * @return 错误条数
     */
    private int checkAuditChiFieldSaveBatch(String chinResultId,
                                            List<DapDataModelTableField> fields) {
        AtomicInteger markErrorFieldSize = new AtomicInteger(0);
        List<DapAuditFieldChinResult> fieldChinResults = fields.parallelStream().map(field -> {
            DapAuditFieldChinResult fieldChinResult = new DapAuditFieldChinResult();
            fieldChinResult.setFieldId(field.getId());
            fieldChinResult.setFieldNewestId(field.getPId());
            fieldChinResult.setFieldName(field.getFieldName());
            String fieldChiName = field.getComment();
            fieldChinResult.setChinResultId(chinResultId);
            fieldChinResult.setFieldChinName(fieldChiName);
            if (StringUtils.isBlank(fieldChiName)) {
                fieldChinResult.setIsPassed(0);
                fieldChinResult.setReason("字段中文名称为空");
                markErrorFieldSize.incrementAndGet();
            } else {
                fieldChinResult.setIsPassed(1);
            }
            return fieldChinResult;
        }).collect(Collectors.toList());
        if (!fieldChinResults.isEmpty()){
            auditFieldChinResultService.saveBatch(fieldChinResults);
        }
        return markErrorFieldSize.get();
    }

}
